<template>
	<view>
		<!-- 表格 -->
		<u-table>
			<u-tr>
				<u-th :width="indexWidth">序号</u-th>
				<u-th :width="warnCodeWidth">code</u-th>
				<u-th :width="warnMsgWidth">错误描述</u-th>
				<u-th :width="warnTimeWidth">时间</u-th>
			</u-tr>
			<!-- 使用 v-for 生成当前页数据 -->
			<u-tr v-for="(item, index) in currentPageData" :key="index">
				<u-td :width="indexWidth" class="max-height-cell">{{ (currentPage-1)*10+index+1 }}</u-td>
				<u-td :width="warnCodeWidth" class="max-height-cell">{{ item.code }}</u-td>
				<u-td :width="warnMsgWidth" class="max-height-cell">{{ item.description }}</u-td>
				<u-td :width="warnTimeWidth" class="max-height-cell">{{ item.time }}</u-td>
			</u-tr>
		</u-table>

		<view class="search-container">
			<u-select v-model="showWarn" :list="warnList" mode="single-column" @confirm="updateWarn"></u-select>
			<u-calendar v-model="showDate" :mode="mode" @change="updateDate"></u-calendar>
			<view class="flexContainer">
				<div class="myFlex">
					<u-icon name="warning-fill"></u-icon>
					<div @click="showWarn = true">{{warnMsg}}</div>
				</div>

				<div class="myFlex">
					<u-icon name="calendar-fill"></u-icon>
					<div @click="showDate = true">时间：{{dateMsg}}</div>
				</div>

				<div class="myFlex">
					<u-icon name="order"></u-icon>
					<div @click="getAll">所有记录</div>
				</div>

			</view>

		</view>

		<!-- 分页按钮 -->
		<view class="fixed-pagination">
			<u-button size="mini" @click="prevPage" :disabled="currentPage === 1">上一页</u-button>
			<u-button size="mini" @click="nextPage" :disabled="currentPage === totalPages">下一页</u-button>
		</view>
		<!-- 显示当前页和最大页 -->
		<view class="page-info">
			<span>当前页: {{ currentPage }}</span>
			<span>总页数: {{ totalPages }}</span>
			<span>总数: {{ dataList.length }}</span>

		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	export default {

		created() {
			this.getAll()

		},
		data() {

			return {
				showWarn: false,
				warnMsg: '全部',
				showDate: false,
				warnValue: 4,
				dates: this.getDates(),
				dateMsg: this.getDateMsg(),
				mode: 'date',
				warnList: [{
						value: '4',
						label: '全部'
					},
					{
						value: '0',
						label: '温度'
					}, {
						value: '1',
						label: '湿度'
					},
					{
						value: '2',
						label: '烟雾'
					}, {
						value: '3',
						label: '火焰'
					}
				],
				indexWidth: "10%",
				warnCodeWidth: "10%",
				warnMsgWidth: "50%",
				warnTimeWidth: "30%",
				dataList: [],
				itemsPerPage: 10,
				currentPage: 1,
			};
		},
		computed: {
			// 计算属性：根据当前页和每页条数动态生成当前页的数据
			currentPageData() {
				const startIdx = (this.currentPage - 1) * this.itemsPerPage;
				const endIdx = startIdx + this.itemsPerPage;
				return this.dataList.slice(startIdx, endIdx);
			},
			// 计算属性：计算总页数
			totalPages() {
				return Math.ceil(this.dataList.length / this.itemsPerPage);
			},
		},
		methods: {
			getAll() {
				let deviceId;
				try {
					deviceId = uni.getStorageSync('deviceId');
				} catch (e) {
					// error
					console.log(e.message)
				}
				deviceId = parseInt(deviceId, 10)
				uni.request({
					url: `${this.$store.state.ipAddr}/historyCode`, //仅为示例，并非真实接口地址。
					data: {
						deviceId: deviceId
					},

					success: (res) => {

						res = res.data
						if (res.code == 200) {
							// 将得到的数据转为datalist
							this.dataList = res.data.map(item => ({
								code: item.code,
								description: item.msg.join(';'), // 将数组合并为以分号分隔的字符串
								time: item.createTime,
							}));
							this.$refs.uToast.show({
								title: '获取成功！',
								type: 'success',
							})
						} else {
							// 请求失败的处理
							console.error('请求失败', res.msg);
						}
					},
				});
			},
			// 上一页按钮点击事件
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
				}
			},
			// 下一页按钮点击事件
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
				}
			},

			updateWarn(res) {

				this.warnValue = res[0].value
				this.warnMsg = res[0].label
		
				//根据code，日期，请求
				let deviceId;
				try {
					deviceId = uni.getStorageSync('deviceId');
				} catch (e) {
					// error
					console.log(e.message)
				}
				deviceId = parseInt(deviceId, 10)

				let startTime = this.dates[0]
				let endTime = this.dates[1]
				let code = res[0].value
				console.log("startTime,endTime,code:", startTime, endTime, code)
				uni.request({
					url: `${this.$store.state.ipAddr}/historyCode`, //仅为示例，并非真实接口地址。
					data: {
						deviceId: deviceId,
						startTime: startTime,
						endTime: endTime,
						code: code
					},

					success: (res) => {

						res = res.data
						if (res.code == 200) {
							// 将得到的数据转为datalist
							this.dataList = res.data.map(item => ({
								code: item.code,
								description: item.msg.join(';'), // 将数组合并为以分号分隔的字符串
								time: item.createTime,
							}));
							this.$refs.uToast.show({
								title: '获取成功！',
								type: 'success',
							})
						} else {
							// 请求失败的处理
							console.error('请求失败', res.msg);
						}
					},
				});

			},
			updateDate(res) {
				//修改日期的值
				const today = new Date(res.year, res.month - 1, res.day); // Month is 0-based in JavaScript Dates
				const tomorrow = new Date(today);
				tomorrow.setDate(today.getDate() + 1);

				const formatDate = (date) => {
					const year = date.getFullYear();
					const month = (date.getMonth() + 1).toString().padStart(2, '0');
					const day = date.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${day} 00:00:00`;
				};
				this.dates = [formatDate(today), formatDate(tomorrow)]
				this.dateMsg = res.result

				//请求
				//根据code，日期，请求
				let deviceId;
				try {
					deviceId = uni.getStorageSync('deviceId');
				} catch (e) {
					// error
					console.log(e.message)
				}
				deviceId = parseInt(deviceId, 10)

				let startTime = this.dates[0]
				let endTime = this.dates[1]
				let code = this.warnValue
				console.log("startTime,endTime,code:", startTime, endTime, code)
				uni.request({
					url: `${this.$store.state.ipAddr}/historyCode`, //仅为示例，并非真实接口地址。
					data: {
						deviceId: deviceId,
						startTime: startTime,
						endTime: endTime,
						code: code
					},

					success: (res) => {

						res = res.data
						console.log(res.data)
						if (res.code == 200) {
							// 将得到的数据转为datalist
							this.dataList = res.data.map(item => ({
								code: item.code,
								description: item.msg.join(';'), // 将数组合并为以分号分隔的字符串
								time: item.createTime,
							}));
							this.$refs.uToast.show({
								title: '获取成功！',
								type: 'success',
							})
						} else {
							// 请求失败的处理
							console.error('请求失败', res.msg);
						}
					},
				});
			},
			getDates() {
				let date = new Date();
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				let hours = date.getHours().toString().padStart(2, '0');
				let minutes = date.getMinutes().toString().padStart(2, '0');
				let seconds = date.getSeconds().toString().padStart(2, '0');

				let todayDateMsg = `${year}-${month}-${day} 00:00:00`;

				// Calculate tomorrow's date
				let tomorrow = new Date();
				tomorrow.setDate(date.getDate() + 1);
				let tomorrowYear = tomorrow.getFullYear();
				let tomorrowMonth = (tomorrow.getMonth() + 1).toString().padStart(2, '0');
				let tomorrowDay = tomorrow.getDate().toString().padStart(2, '0');
				let tomorrowDateMsg = `${tomorrowYear}-${tomorrowMonth}-${tomorrowDay} 00:00:00`;

				return [todayDateMsg, tomorrowDateMsg];
			},
			getDateMsg() {
				let date = new Date();
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				let hours = date.getHours().toString().padStart(2, '0');
				let minutes = date.getMinutes().toString().padStart(2, '0');
				let seconds = date.getSeconds().toString().padStart(2, '0');

				let todayDateMsg = `${year}-${month}-${day}`;
				return todayDateMsg;
			}
		},
	};
</script>

<style>
	.search-container {
		position: fixed;
		bottom: 90px;
		/* 调整为你想要的底部间距 */
		left: 15px;
		right: 15px;
		background-color: #fff;
		padding: 15px;
		z-index: 1;
	}

	.fixed-pagination {
		position: fixed;
		bottom: 60px;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		justify-content: space-between;
		width: 200px;
		/* 调整按钮容器的宽度 */
	}

	.fixed-pagination u-button {
		flex-grow: 1;
	}

	.max-height-cell {
		max-height: 60px;
		min-height: 60px;
		/* 设置单元格最大高度 */
		overflow: hidden;
		text-overflow: ellipsis;
		/* 超出部分显示省略号 */
	}

	.page-info {
		position: fixed;
		bottom: 25px;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		justify-content: space-between;
		width: 200px;
		color: #888;

		/* 调整颜色为灰色 */
	}

	.page-info span {
		flex-grow: 1;
		text-align: center;
		/* 让文本居中对齐 */
	}

	.flexContainer {
		display: flex;
	}


	.myFlex {
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
		margin-right: 20px;
		/* 设置两个元素之间的右边距 */
	}

	.myFlex div {
		cursor: pointer;
		/* 鼠标悬停显示手型 */
		margin-left: 5px;
		/* 设置图标和文本之间的左边距 */
	}
</style>